<template>
  <div>
    <el-card>
      <template #header>
        <span class="title">作品总数 {{ createdCount }}，发布 {{ publishedCount }}</span>
      </template>
      <el-row>
        <el-col :span="12">
          <v-chart style="height: 500px" :option="pieOption" :theme="isDark ? 'dark' : ''" autoresize />
        </el-col>
        <el-col :span="12">
          <v-chart style="height: 500px" :option="barOption" :theme="isDark ? 'dark' : ''" autoresize />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { getCount, getMonthlyCount, MonthlyDataProps } from '@/service/works'
import { useGlobalStore } from '@/stores/global'
// import { ECharts } from 'echarts'

const global = useGlobalStore()
const isDark = computed(() => global.isDark)
const createdCount = ref(0)
const publishedCount = ref(0)
const pieOption = ref()
const barOption = ref()

onMounted(async () => {
  const { created, published } = await getCount()
  createdCount.value = created
  publishedCount.value = published

  const rawData = await getMonthlyCount()
  pieOption.value = parsePieOpt(rawData)
  barOption.value = parseMonthlyOpt(rawData)
})

function parsePieOpt(data: Array<MonthlyDataProps>) {
  let created = 0
  let published = 0
  for (const item of data) {
    const itemData = item.data
    created += itemData.created || 0
    published += itemData.published || 0
  }
  return {
    title: {
      text: '发布占比',
      top: 10,
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '10%',
      data: ['待发布', '发布']
    },
    series: [
      {
        // name: '发布占比',
        type: 'pie',
        radius: '65%',
        center: ['50%', '60%'],
        data: [
          { value: created - published, name: '待发布' },
          { value: published, name: '发布' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
}

// 默认 一年的时间范围
function parseMonthlyOpt(data: Array<MonthlyDataProps>) {
  const arr = data.map(item => {
    const { month, data: monthData } = item
    return [month, monthData.created, monthData.published]
  })

  return {
    title: {
      text: '每月作品创建和发布',
      top: 10,
      left: 'center'
    },
    legend: {
      top: '10%'
    },
    tooltip: {},
    grid: {
      top: 140,
      bottom: 40
    },
    dataset: {
      source: [['月', '创建', '发布'], ...arr]
    },
    xAxis: { type: 'category' },
    yAxis: {},
    // barWidth: '10%'
    series: [{ type: 'bar' }, { type: 'bar' }]
  }
}
</script>
<style lang="scss" scoped></style>
